package com.eascs.admin.o2o.oaotodata.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.eascs.account.account.AccountEntity;
import com.eascs.account.api.IAccountService;
import com.eascs.account.api.IFeeService;
import com.eascs.account.api.constants.enums.LoanAccountType;
import com.eascs.account.api.constants.enums.TradeDirection;
import com.eascs.account.api.constants.enums.TradeType;
import com.eascs.account.api.vo.FeeManualVO;
import com.eascs.account.api.vo.TradeParamsVO;
import com.eascs.admin.common.service.BaseSevice;
import com.eascs.admin.common.utils.AccountConstants;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oChargeSituationService;
import com.eascs.admin.o2o.loanAccount.entity.O2oLoanapplyAccountEntity;
import com.eascs.admin.o2o.loanAccount.serviceimpl.O2oLoanapplyAccountImpl;
import com.eascs.admin.o2o.oaotodata.dao.O2oComDataDao;
import com.eascs.admin.o2o.oaotodata.dao.OaComDataDao;
import com.eascs.admin.o2o.oaotodata.entity.OaO2oLoanapply;
import com.eascs.admin.o2o.oaotodata.form.AccLoanapplyForm;
import com.eascs.admin.o2o.oaotodata.trans.O2oOATransEntity;
import com.eascs.admin.o2o.zx.entity.O2oLoanUserEntityZx;
import com.eascs.admin.o2o.zx.vo.O2oZxUserVo;
import com.eascs.admin.oldO2olike.form.OldO2oLikeForm;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.workflow.common.vo.ModelResult;

/**
* @author bao.pan 2016年12月23日 上午9:57:58
*/
@Service
public class OaO2oDataService extends BaseSevice{
	private final Logger logger = LoggerFactory.getLogger(OaO2oDataService.class);
	@Autowired
	private O2oComDataDao o2oComDataDao;
	@Autowired
	private OaComDataDao oaComDataDao;
	@Reference
	private IAccountService iAccountService;
	@Reference
	private IFeeService iFeeService;
	@Autowired
	private O2oLoanapplyAccountImpl o2oLoanapplyAccountImpl;
	@Autowired
	private O2oChargeSituationService o2oChargeSituationService;
	public List<OaO2oLoanapply> OaOrO2oloanapply(){
		int num=o2oComDataDao.findbyloanapplyno();
		List<OaO2oLoanapply> list=oaComDataDao.findoaORo2odateLoanapply(num);
//		O2oLoanapplyEntity o2o=O2oOATransEntity.OAorO2oLoanapplyEntity(list.get(0));
//		
//		int num=o2oComDataDao.INSERTloanapply(o2o);
////		for (OaO2oLoanapply oaO2oLoanapply : list) {
////			
////		}
		return list;
	}
	
	public int INSERTloanapply(O2oLoanapplyEntity o2o){
		return o2oComDataDao.insert(o2o);
	}
	
	public String findpaydate(int eaid){
		return oaComDataDao.findpaydate(eaid);
	}
	public PageResult<O2oZxUserVo> findZXByPage(OldO2oLikeForm oldO2oLikeForm) {
		return o2oComDataDao.findZXByPage(oldO2oLikeForm);
	}
	/**
	 *未放款有收费未退
	 * @param oldO2oLikeForm
	 * @return
	 */
	public void findwfByPage1() {
		StringBuffer querySql=new StringBuffer();
		querySql.append(" SELECT y.loanapply_no as loanapplyno,y.bill_code as billcode,a.account_no as accountno, ");
		querySql.append("e.red_manger-IFNULL(e.reta_manage,0) as redmanger,");
		querySql.append("e.red_deposite-IFNULL(e.reta_deposite,0) as reddeposite,");
		querySql.append("e.red_risk-IFNULL(e.reta_risk ,0) as redrisk,e.pay_date as paydate ");
		querySql.append(" from o2o_loanapply y,o2o_loanapply_expand e,o2o_loanapply_account a ");
		querySql.append(" where y.loanapply_no=e.loanapply_no and y.loanapply_no=a.loanapply_no ");
		querySql.append(" and e.bill_status ='CLO' and y.loan_flg='N' and a.account_no is not null ");
		int pageIndex = 0;
		int pageSize = 100;
		while (pageIndex >= 0) {
			logger.info("未放款有收费未退任务运行中任务运行中，正在查询第[{}]页数据", pageIndex);
			SqlPageQuery<AccLoanapplyForm> sqlPageQuery = new SqlPageQuery<>(AccLoanapplyForm.class, pageSize,
					pageIndex, querySql.toString());
			PageResult<AccLoanapplyForm> results = o2oComDataDao.findDataWithPage(sqlPageQuery);

			List<AccLoanapplyForm> list = results.getData();
			
			for (AccLoanapplyForm acc : list) {
				
				ModelResult<List<AccountEntity>> acclist=iAccountService.queryIndividualAccount(acc.getAccountno());
				if (acclist.isSuccess()) {
//					acclist.getModel().get(0).getAccount();
					for (AccountEntity accountEntity : acclist.getModel()) {
						FeeManualVO paramsVO = new FeeManualVO();
						paramsVO.setAccount(accountEntity.getAccount());
						paramsVO.setTradeDirection(TradeDirection.IN);
						paramsVO.setTradeDate(acc.getPaydate());
						paramsVO.setRemark("数椐初始化,单号："+acc.getBillcode());
						//保证金
						if (accountEntity.getAccountTypeCode().equals(LoanAccountType.DEPOSIT.getTypeCode())) {
							paramsVO.setAmount(acc.getReddeposite());
							paramsVO.setTradeType(TradeType.FEE_DEPOSIT);
						}
						//管理费
						if (accountEntity.getAccountTypeCode().equals(LoanAccountType.ISTRATION.getTypeCode())) {
							paramsVO.setAmount(acc.getRedmanger());
							paramsVO.setTradeType(TradeType.FEE_ISTRATION);
						}
						//风险补偿金
						if (accountEntity.getAccountTypeCode().equals(LoanAccountType.COMPENSATION.getTypeCode())) {
							paramsVO.setAmount(acc.getRedrisk());
							paramsVO.setTradeType(TradeType.FEE_COMPENSATION);
						}
						ModelResult<Boolean> result=iFeeService.feeManual(paramsVO);
						logger.info("未放款有收费未退={}:{}，子帐号={},账户类型={}", result.isSuccess(), result.getErrMsg(),
								accountEntity.getAccount(), accountEntity.getAccountTypeCode());
					}
					logger.info("未放款有收费未退={}",JSON.toJSON(acclist.getModel()) );
				}
			}
			pageIndex++;
			if (results.getPageTotal() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("未放款有收费未退任务运行中入库任务结束=============");
	}
	/**
	 *已放款未结清有收费未退
	 * @param oldO2oLikeForm
	 * @return
	 */
	public void findwfByPage2() {
		StringBuffer querySql=new StringBuffer();
//		querySql.append(" SELECT y.loanapply_no as loanapplyno,y.bill_code as billcode,a.account_no as accountno, ");
//		querySql.append("e.red_manger-IFNULL(e.reta_manage,0) as redmanger,");
//		querySql.append("e.red_deposite-IFNULL(e.reta_deposite,0) as reddeposite,");
//		querySql.append("e.red_risk-IFNULL(e.reta_risk ,0) as redrisk,e.pay_date as paydate ");
//		querySql.append(" from o2o_loanapply y,o2o_loanapply_expand e,o2o_loanapply_account a ");
//		querySql.append(" where y.loanapply_no=e.loanapply_no and y.loanapply_no=a.loanapply_no ");
//		querySql.append(" and e.bill_status ='CLO' and y.loan_flg='Y' and y.wf_type!='HN' and a.account_no is not null ORDER BY y.create_date ASC ");
		querySql.append(" SELECT * FROM ( ");
		querySql.append(" select @rownum:=@rownum+1 as rownum ,t.* from (");
		querySql.append(" SELECT @rownum:=0 as a,y.loanapply_no as loanapplyno,y.bill_code as billcode,a.account_no as accountno,");
		querySql.append(" e.red_manger-IFNULL(e.reta_manage,0) as redmanger,");
		querySql.append(" e.red_deposite-IFNULL(e.reta_deposite,0) as reddeposite,");
		querySql.append(" e.red_risk-IFNULL(e.reta_risk ,0) as redrisk,e.pay_date as paydate");
		querySql.append(" from o2o_loanapply y,o2o_loanapply_expand e,o2o_loanapply_account a");
		querySql.append(" where y.loanapply_no=e.loanapply_no and y.loanapply_no=a.loanapply_no ");
		querySql.append(" and e.bill_status ='CLO' and y.loan_flg='Y' and y.wf_type!='HN' and a.account_no is not null  ORDER BY y.create_date ASC");
		querySql.append(" ) t  ");
		querySql.append(" ) t1 where rownum>0 ");
		int pageIndex = 0;
		int pageSize = 100;
		while (pageIndex >= 0) {
			logger.info("已放款未结清有收费未退任务运行中任务运行中，正在查询第[{}]页数据", pageIndex);
			SqlPageQuery<AccLoanapplyForm> sqlPageQuery = new SqlPageQuery<>(AccLoanapplyForm.class, pageSize,
					pageIndex, querySql.toString());
			PageResult<AccLoanapplyForm> results = o2oComDataDao.findDataWithPage(sqlPageQuery);

			List<AccLoanapplyForm> list = results.getData();
			
			for (AccLoanapplyForm acc : list) {
				
				ModelResult<List<AccountEntity>> acclist=iAccountService.queryIndividualAccount(acc.getAccountno());
				
				if (acclist.isSuccess()) {
//					acclist.getModel().get(0).getAccount();
					for (AccountEntity accountEntity : acclist.getModel()) {
						FeeManualVO paramsVO = new FeeManualVO();
						paramsVO.setTradeDirection(TradeDirection.IN);
						paramsVO.setTradeDate(acc.getPaydate());
						//保证金
						if (accountEntity.getAccountTypeCode().equals(LoanAccountType.DEPOSIT.getTypeCode())) {
							paramsVO.setAccount(accountEntity.getAccount());
							paramsVO.setAmount(acc.getReddeposite());
							paramsVO.setTradeType(TradeType.FEE_DEPOSIT);
							paramsVO.setRemark("数椐初始化,单号："+acc.getBillcode());
						}
						//管理费
						if (accountEntity.getAccountTypeCode().equals(LoanAccountType.ISTRATION.getTypeCode())) {
							paramsVO.setAccount("1200000001");
							paramsVO.setAmount(acc.getRedmanger());
							paramsVO.setTradeType(TradeType.FEE_COMPANY);
							paramsVO.setRemark("管理费数椐初始化,单号："+acc.getBillcode());
						}
						//风险补偿金
						if (accountEntity.getAccountTypeCode().equals(LoanAccountType.COMPENSATION.getTypeCode())) {
							paramsVO.setAccount("1200000001");
							paramsVO.setAmount(acc.getRedrisk());
							paramsVO.setTradeType(TradeType.FEE_COMPANY);
							paramsVO.setRemark("风险补偿金数椐初始化,单号："+acc.getBillcode());
						}
						ModelResult<Boolean> result=iFeeService.feeManual(paramsVO);
						logger.info("已放款未结清有收费未退={}:{}", result.isSuccess(), result.getErrMsg());
						if (!result.isSuccess()) {
							return;
						}
					}
				}
				logger.info("已放款未结清有收费未退查询帐号={}:{}", acclist.isSuccess(), acclist.getErrMsg());
				logger.info("已放款未结清有收费未退,第几条{}数椐，查询单号={}",acc.getRownum(), acc.getBillcode());
			}
			pageIndex++;
			if (results.getPageTotal() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("已放款未结清有收费未退任务运行中入库任务结束=============");
	}
	/**
	 *已结清有收费未退
	 * @param oldO2oLikeForm
	 * @return
	 */
	public void findwfByPage3() {
		StringBuffer querySql=new StringBuffer();
		querySql.append("SELECT * FROM ( ");
		querySql.append(" select @rownum:=@rownum+1 as rownum ,t.* from ( ");
		querySql.append(" SELECT @rownum:=0 as a, y.loanapply_no as loanapplyno,y.bill_code as billcode,a.account_no as accountno, ");
		querySql.append(" IFNULL(e.red_manger,0)-IFNULL(e.reta_manage,0) as redmanger,");
		querySql.append(" IFNULL(e.red_deposite,0)-IFNULL(e.reta_deposite,0) as reddeposite,");
		querySql.append(" IFNULL(e.red_risk,0)-IFNULL(e.reta_risk ,0) as redrisk,e.pay_date as paydate,y.loan_id as loanid ");
		querySql.append(" from o2o_loanapply y,o2o_loanapply_expand e,o2o_loanapply_account a");
		querySql.append(" where y.loanapply_no=e.loanapply_no and y.loanapply_no=a.loanapply_no ");
		querySql.append(" and e.bill_status ='CLO' and y.loan_flg='Y' and y.wf_type='HN' and a.account_no is not null ORDER BY y.create_date ASC ");
		querySql.append(" ) t ");
		querySql.append(" ) t1 where rownum>3948 ");
		int pageIndex = 0;
		int pageSize = 100;
		while (pageIndex >= 0) {
			logger.info("已结清有收费未退任务运行中任务运行中，正在查询第[{}]页数据", pageIndex);
			SqlPageQuery<AccLoanapplyForm> sqlPageQuery = new SqlPageQuery<>(AccLoanapplyForm.class, pageSize,
					pageIndex, querySql.toString());
			PageResult<AccLoanapplyForm> results = o2oComDataDao.findDataWithPage(sqlPageQuery);

			List<AccLoanapplyForm> list = results.getData();
			
			for (AccLoanapplyForm acc : list) {
				
				AccountEntity aEntity=o2oChargeSituationService.queryByLoanId(acc.getLoanid(), null, "21");
				
				FeeManualVO paramsVO = new FeeManualVO();
				paramsVO.setTradeDirection(TradeDirection.IN);
				paramsVO.setTradeDate(acc.getPaydate());
				//管理费
				paramsVO.setAccount("1200000001");
				paramsVO.setAmount(acc.getRedmanger());
				paramsVO.setTradeType(TradeType.FEE_COMPANY);
				paramsVO.setRemark("管理费数椐初始化,单号："+acc.getBillcode());
//				logger.info("已结清有收费未退查询帐号json={}",JSON.toJSON(paramsVO) );
				ModelResult<Boolean> result=iFeeService.feeManual(paramsVO);
				logger.info("已结清有收费未退查询帐号;管理费数椐初始化={}:{}:{}", result.isSuccess(), result.getErrMsg());			
				if (!result.isSuccess()) {
					return;
				}
				//风险补偿金
				paramsVO.setAmount(acc.getRedrisk());
				paramsVO.setRemark("风险补偿金数椐初始化,单号："+acc.getBillcode());
				ModelResult<Boolean> result1=iFeeService.feeManual(paramsVO);
				logger.info("已结清有收费未退查询帐号;风险补偿金数椐初始化={}:{}", result1.isSuccess(), result1.getErrMsg());
				if (!result1.isSuccess()) {
					return;
				}
				//保证金
				if (aEntity!=null) {
					if (!StringUtils.isEmpty(aEntity.getAccount())) {
						paramsVO.setAccount(aEntity.getAccount());
						paramsVO.setAmount(acc.getReddeposite());
						paramsVO.setTradeType(TradeType.FEE_PAYMENT);
						paramsVO.setRemark("结清保证金数椐初始化,单号："+acc.getBillcode());
						ModelResult<Boolean> result2=iFeeService.feeManual(paramsVO);
						logger.info("已结清有收费未退查询帐号;结清保证金数椐初始化={}:{}", result2.isSuccess(), result2.getErrMsg());
						if (result2.isSuccess()) {
							O2oLoanapplyAccountEntity o2oaccentity=	o2oLoanapplyAccountImpl.getEntityByLoanapplyNo(acc.getLoanapplyno());
							o2oaccentity.setJqstatus("1");
							o2oLoanapplyAccountImpl.update(o2oaccentity);
						}else {
							return;
						}
					}
				}else{
					logger.info("已结清有收费未退,aEntity为空！");
					return;
				}
				
				logger.info("已结清有收费未退,第几条{}数椐，查询单号={}",acc.getRownum(), acc.getBillcode());
//				iAccountService.queryAccount(String id, String code);
			}
			pageIndex++;
			if (results.getPageTotal() <= pageIndex) {
				pageIndex = -1;
			}
		}
		logger.info("已放款未结清有收费未退任务运行中入库任务结束=============");
	}
}
